<?php

/*
 *  This file is part of Urd.
 *
 *  Urd is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 3 of the License, or
 *  (at your option) any later version.
 *  Urd is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program. See the file "COPYING". If it does not 
 *  exist, see <http://www.gnu.org/licenses/>.
 * 
 * $LastChangedDate: 2008-07-02 19:40:56 +0200 (Wed, 02 Jul 2008) $
 * $Rev: 1256 $
 * $Author: gavinspearhead $
 * $Id: admin_users.php 1256 2008-07-02 17:40:56Z gavinspearhead $
 */


define('ORIGINAL_PAGE', $_SERVER['PHP_SELF']);

$__auth = 'silent';


$name_pattern = '[ a-zA-Z0-9_\-.():,@!$%^&*+=]';
$hostname_pattern = '[a-zA-Z0-9.\-_:\[\]]';

class usenet_servers_c {
	public $edit;
	public $id;
	public $name;
	public $hostname;
	public $port;
	public $sec_port;
	public $authentication;
	public $username;
	public $password;
	public $threads;
	public $connection;
	public $retention;
	public $compressed_headers;
    public $connection_raw;
    public $posting;
	public $priority; // 1 is highest, 100 is lowest; 0 = disabled
	function __construct ($edit, $id='', $n='', $h='', $p=119, $sp=563, $a=FALSE, $t=3, $c='off', $cr= 'off', $u='', $pw='', $priority=10, $ch=0, $r=0, $post=FALSE)
	{
		assert((is_numeric($id)|| $id=='') && is_numeric($p) && is_numeric($sp) && is_bool($a) && is_numeric($priority));
		$this->edit = $edit;
		$this->id = $id;
		$this->name = $n;
		$this->hostname = $h;
		$this->port = $p;
		$this->sec_port = $sp;
		$this->authentication = $a;
		$this->threads = $t;
		$this->connection = $c;
		$this->connection_raw = $cr;
		$this->username = $u;
		$this->password = $pw;
		$this->compressed_headers = $ch;
		$this->active = $priority > 0;
        $this->priority = $priority;
        $this->posting = $post;
		$this->retention = $r;
	}
};


$pathaeus = realpath(dirname(__FILE__));
require_once "$pathaeus/../functions/ajax_includes.php";
require_once "$pathaeus/../functions/functions.php";
require_once "$pathaeus/../functions/urd_log.php";
require_once "$pathaeus/../functions/pref_functions.php";

if (!$isadmin)  
	die_html ($LN['error_noadmin']);


$prefs = load_prefs_clean($db, $userID); // load the prefs
$prefs_root = load_config($db);
$connection_types = array ('off'=>$LN['off'], 'ssl'=>'SSL', 'tls'=>'TLS');

$cmd = isset($_REQUEST['cmd'])?$_REQUEST['cmd']:'';
$id = isset($_REQUEST['id'])?$_REQUEST['id']:'';

$db->escape($cmd);
$db->escape($id);

switch (strtolower($cmd)) {

case 'import_settings':
    if(isset ($_FILES['filename']['tmp_name'])) {
        try {
        $xml = new urd_xml_reader($_FILES['filename']['tmp_name']);
        $usenet_servers = $xml->read_usenet_servers($db);
        if ($usenet_servers != array()) {
            clear_all_usenet_servers($db);
            set_all_usenet_servers($db, $usenet_servers);
            $prefs = $prefs_root;
            stop_urdd();
            usleep(500000);
            start_urdd(); 
            redirect('admin_usenet_servers.php');
        }
        } catch (exception $e) {
//            echo_debug_trace($e, 255);
        }
    }
    break;
case 'export_settings':
    header('Content-Type: text/html/force-download');
    header('Content-Disposition: attachment; filename=urd_usenet_servers_settings.xml');
    $xml = new urd_xml_writer('php://output');
    $xml->write_usenet_servers($db);
    $xml->output_xml_data();
    die;

break;

case 'delete_server':
	verify_challenge($_POST['challenge']);
	delete_usenet_server($db, $id); 
	$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
	if ($uc->is_connected()) {
		$uc->set('server', 'delete', $id);
		usleep(50000);
	} 
    break;
case 'disable_posting':
	verify_challenge($_POST['challenge']);
	$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
    if ($uc->is_connected()) {
        $uc->set('server', 'noposting', $id);
        usleep(50000);
    } else
        set_posting($db, $id, FALSE);
    break;
case 'enable_posting':
    verify_challenge($_POST['challenge']);
    $uc = new urdd_client($prefs_root['urdd_host'], $prefs_root['urdd_port'],$userID);
	if ($uc->is_connected()) {
		$uc->set('server', 'posting', $id);
		usleep(50000);
	} else {
        set_posting($db, $id, TRUE);
	}
	break;

case 'enable_server':
	verify_challenge($_POST['challenge']);
	$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
	$prio = DEFAULT_USENET_SERVER_PRIORITY;
	if ($uc->is_connected()) {
		$uc->set('server', $id, $prio);
		usleep(50000);
	} else {
		enable_usenet_server($db, $id, $prio);
	}

	break;
case 'disable_server':
	verify_challenge($_POST['challenge']);
	$uc = new urdd_client($prefs_root['urdd_host'], $prefs_root['urdd_port'],$userID);
    $prio = DISABLED_USENET_SERVER_PRIORITY;
    if ($uc->is_connected()) {
        $uc->set('server', $id, $prio);
        usleep(50000);
    } else
        disable_usenet_server($db, $id);

    break;
case 'set_preferred':
    verify_challenge($_POST['challenge']);
	if (!is_numeric($id))  {
		die_html($LN_nosuchserver);
	}
	$sql = "SELECT COUNT(*) AS cnt FROM usenet_servers WHERE \"id\" = '$id'";
	$res = $db->execute_query($sql);
	if ($res === FALSE) {
		die_html($LN_nosuchserver); 
	}
	if ($res[0]['cnt'] != 1) {
		die_html($LN_nosuchserver); 
	}
	$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
	if ($uc->is_connected()) {
		$uc->set('preferred', $id);
		usleep(50000);
	} else
		set_config($db, 'preferred_server', $id);

	break;
case 'showeditusenetserver':
	if (is_numeric($id)) {
		$sql = "SELECT * FROM usenet_servers WHERE \"id\" = '$id'";
        $res = $db->execute_query($sql);
		$name = $res [0]['name'];
		$username = $res [0]['username'];
		$hostname = $res [0]['hostname'];
		$password = $res [0]['password'];
		$port = $res[0]['port'];
		$threads = $res[0]['threads'];
		$sec_port = $res[0]['secure_port'];
		$authentication = $res[0]['authentication'];
		$priority = $res[0]['priority'];
		$connection = $res[0]['connection'];
        $retention = $res[0]['retention'];
        $posting = $res[0]['posting'];
        $compressed_headers = $res[0]['compressed_headers'];
	} else if ($id == 'new') {
		$name = ''; 
		$username = ''; 
		$retention = ''; 
		$hostname = '';
		$password = '';
		$threads = 1;
		$port = 119;
		$sec_port = 563 ;
		$authentication = 0;
		$priority = 0;
		$connection = 'off'; 
        $compressed_headers = 0;
        $posting = 0;

	} else
		die_html ('Unknown ID');

	$challenge = set_challenge();
	$smarty->assign('challenge',    $challenge);
	$smarty->assign('id', $id);
	$smarty->assign('name', $name);
	$smarty->assign('connection_types',    $connection_types);
	$smarty->assign('hostname', $hostname);
	$smarty->assign('username', $username);
	$smarty->assign('password', $password);
	$smarty->assign('retention', $retention);
	$smarty->assign('compressed_headers', $compressed_headers);
	$smarty->assign('text_box_size', TEXT_BOX_SIZE);
	$smarty->assign('number_box_size', NUMBER_BOX_SIZE);
	$smarty->assign('port', $port);
	$smarty->assign('posting', $posting);
	$smarty->assign('threads', $threads);
	$smarty->assign('sec_port', $sec_port);
	$smarty->assign('authentication', $authentication);
	$smarty->assign('priority', $priority);
	$smarty->assign('connection', $connection);
	$smarty->display('ajax_edit_usenet_servers.tpl');
	die();

	break;

case 'update_usenet_server':
	verify_challenge_text($_REQUEST['challenge']);
	if (is_numeric($id) || $id == 'new') {
        $error = '';
		$priority = $port = $sec_port = $threads = $authentication = $retention = 0;
		$hostname = $name = $connection = $username = $password = '';
		if (isset($_REQUEST['hostname']))
			$hostname = trim($_REQUEST['hostname']);
		if (isset($_REQUEST['name']))
			$name = trim($_REQUEST['name']);
		if (isset($_REQUEST['secure_port'])) 
			$sec_port = ($_REQUEST['secure_port']);
		if (isset($_REQUEST['port'])) 
			$port = ($_REQUEST['port']);
		if (isset($_REQUEST['priority'])) 
			$priority = ($_REQUEST['priority']);
		if (isset($_REQUEST['threads']))
			$threads = ($_REQUEST['threads']);
		if (isset($_REQUEST['connection']))
			$connection = $_REQUEST['connection'];
		if (isset($_REQUEST['retention']))
			$retention = trim($_REQUEST['retention']);
		$compressed_headers = (isset($_REQUEST['compressed_headers'])&& $_REQUEST['compressed_headers'] == 'on')? 1 : 0;

		$posting =  (isset($_REQUEST['posting'])&& $_REQUEST['posting'] == 'on')? 1 : 0;
       
		if (($error = verify_text($name, $name_pattern)) != '') { 
			die_html($LN['usenet_name'] . ': ' . $error['msg']);
		}
		if (($error = verify_text($hostname, $hostname_pattern)) != '') {
			die_html($LN['usenet_hostname'] . ': ' . $error['msg']); 
		}

		if (($error = verify_numeric_opt($sec_port, TRUE, 0, 65535)) != '') {
			die_html($LN['usenet_secport'] . ': ' . $error['msg']); 
		}

		if (($error = verify_numeric_opt($retention, TRUE, 0, 65535)) != '') {
			die_html($LN['usenet_retention'] . ': ' . $error['msg']); 
		}
		if (($error = verify_numeric_opt($port, TRUE, 0, 65535)) != '') {
			die_html($LN['usenet_port'] . ': ' . $error['msg']); 
		}

		if (($port == '' || $port == 0) && ($sec_port == '' || $sec_port == 0)){
			die_html($LN['error_needatleastoneport']);
		}

		if (($error = verify_numeric_opt($priority, TRUE, 0, 100)) != ''){
			die_html($LN['usenet_priority'] . ': ' . $error['msg']);
		}
		if (($error = verify_numeric($_REQUEST['threads'], 1)) != ''){
			die_html($LN['usenet_threads'] . ': ' . $error['msg']); 
		}

		if (($error = verify_array($_REQUEST['connection'], array_keys($connection_types))) != ''){
			die_html($LN['usenet_connection'] . ': ' . $error['msg']); 
		}
		if ($connection != 'off' && ($sec_port == '' || $sec_port == 0)){
			die_html($LN['error_needsecureport']); 
		}
		if (isset($_REQUEST['authentication']) && $_REQUEST['authentication'] == 'on') {
			$authentication = TRUE;
			if (isset($_REQUEST['username']) && verify_text($_REQUEST['username']) == '') 
				$username = trim($_REQUEST['username']);
			else{
				die_html($LN['error_invalidusername'] . $username); 
			}
			if (isset($_REQUEST['password'])) {
				$password = trim($_REQUEST['password']);
				$pwmsg = verify_text($password);
				if ($pwmsg != ''){
					die_html($pwmsg['msg']); 
				}
			} else{
				die_html($LN['error_invalidpw']); 
			}
		} else {
			$authentication = 0;
			$username = '';
			$password = '';
		}
		if ($id == 'new') {
			$db->escape($name);
			$query = "\"id\" FROM usenet_servers WHERE \"name\"='$name'";
			$res = $db->select_query($query);
			if ($res === FALSE) {
				$id = add_usenet_server($db, $name, $hostname, $port, $sec_port, $threads, $connection, $authentication, $username, $password, $priority, $retention, $compressed_headers, $posting);
				$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
				if ($uc->is_connected()) {
					$uc->set('server', 'load', $id);
				}
			} else {
				die_html ($LN['error_usenetserverexists']); 
			}
		} else if (is_numeric($id)) {
			$query = "\"name\" FROM usenet_servers WHERE \"id\"='$id'";
			$res = $db->select_query($query);
			if ($res !== FALSE) {
				update_usenet_server($db, $id, $name, $hostname, $port, $sec_port, $threads, $connection, $authentication, $username, $password, $priority, $retention, $compressed_headers, $posting);

				$uc = new urdd_client($prefs_root['urdd_host'],$prefs_root['urdd_port'],$userID);
				if ($uc->is_connected()) {
					$uc->set('server', 'reload', $id);
				}
			} else {
				die_html ($LN['error_nosuchserver']); 
			}
		}
	}
	break;
case 'reload_servers':
	try {
		$primary = get_config($db, 'preferred_server');
	} catch (exception $e) {
		$primary = NULL;
	}

	$usenet_servers= array();
	$sql = '* FROM usenet_servers ORDER BY "name" ASC' ;
	$res = $db->select_query($sql);
	if ($res == FALSE)
		$res = array();
	foreach ($res as $row) {
		$id = $row['id'];
		$name = $row['name'];
		$hostname = $row['hostname'];
		$port = $row['port'];
		$sec_port = $row['secure_port'];
		$threads = $row['threads'];
		$conn = (isset($connection_types[$row['connection']])) ?($connection_types[$row['connection']]) :'off' ;
		$conn_raw = $row['connection'];
		$auth = $row['authentication'];
		$username = $row['username'];
		$password = $row['password'];
		$posting = $row['posting'];
		$retention = $row['retention'];
		$compressed_headers = $row['compressed_headers'];
		$priority = $row['priority'];
		$usenet_servers[] = new usenet_servers_c(0, $id, $name, $hostname, $port, $sec_port, (bool) $auth, $threads, $conn, $conn_raw, $username, $password, $priority, $compressed_headers, $retention, $posting);
	}
	$challenge = set_challenge();
	$smarty->assign('challenge',    $challenge);
	$smarty->assign('maxstrlen',		$prefs['maxsetname']/2);
	$smarty->assign('usenet_servers',$usenet_servers);
	$smarty->assign('primary', 	$primary);
	$smarty->display('ajax_show_usenet_servers.tpl');
	die;
	break;
default:
	die_html ("O-oh - Unknown command $cmd");
	break;
}

echo 'OK';
?> 
